package com.fg.cloud.manager.service.system.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fg.cloud.common.PageUtils;
import com.fg.cloud.manager.entry.system.CodeRulesEntity;
import com.fg.cloud.manager.entry.system.CoderulesPurposeEntity;
import com.fg.cloud.manager.entry.system.vo.CodeRulesVo;
import com.fg.cloud.manager.mapper.system.CodeRulesMapper;
import com.fg.cloud.manager.service.system.CodeRulesService;

@Service
public class CodeRulesServiceImpl implements CodeRulesService{

	@Autowired
	private  CodeRulesMapper codeRulesMapper;

	@Override
	@Transactional
	public String findRules(Map<String, Object> usmap) {
		// 获取最新一条订单的编号
		Integer origin = (int)usmap.get("origin");
		String orderNo = "";
		if( origin == 0){// 订单
			orderNo = codeRulesMapper.findOrderNo(usmap);
		}else if(origin == 1){//发货单
			orderNo = codeRulesMapper.findDeliveryNo(usmap);
		}else if(origin == 2){//退货单
			orderNo = codeRulesMapper.findReturnNo(usmap);
		}else{// 流水
			orderNo = codeRulesMapper.findRecordNo(usmap);
		}
		
		// 判断是否重置流水号
		Boolean flag = true;// 用于判断是否重置流水
		StringBuffer resetString = new StringBuffer();// 存放数据库中参与流水重置的字段
		StringBuffer findresetString = new StringBuffer();//存放单据编号中参与流水重置的字段
		Integer begin = 0;
		Integer end = 0;
		Map<Integer, Integer> resetMap = new HashMap<Integer, Integer>();// 存放参与流水重置的起始下标和结束下标map<起始下标,结束下标>
		List<CodeRulesVo> list = codeRulesMapper.findRules(usmap);
		if(list.size() == 0){
			return null;
		}
		// 循环获取所有参与流水的字段,用于做对比
		for(int i = 0;i<list.size();i++){
			end = begin + list.get(i).getRuleLength();
			if(list.get(i).getResetFlag() == 1){// 参与流水重置的字段
				if(list.get(i).getRuleCategory() == 3){
					Date currentTime = new Date();
					SimpleDateFormat formatter = new SimpleDateFormat(list.get(i).getCode());
					String dateString = formatter.format(currentTime);
					resetString.append(dateString);
				}else{
					resetString.append(list.get(i).getCode());
				}
				resetMap.put(begin, end);
			}
			begin +=  list.get(i).getRuleLength();
		}
		
		// 长度不一致,直接false
		if(orderNo.length() != end){
			flag = false;
		}else{
			for(int a : resetMap.keySet()){
				findresetString.append(orderNo.substring(a,resetMap.get(a)));
			}
			flag = resetString.toString().equals(findresetString.toString());
		}
		

		StringBuffer sb = new StringBuffer();//存放结果
		Integer length = 0;// 流水长度
		String fillCharacter = "";//填充字符
		String delimiter = list.get(0).getDelimiter();// 分割符号
		Integer step = list.get(0).getStep();;//步长
		for(int i = 0;i<list.size();i++){
			if(list.get(i).getRuleCategory() == 1){// 流水号,流水号重置在此添加
				step = list.get(i).getStep();
				length = list.get(i).getRuleLength();
				fillCharacter = list.get(i).getFillCharacter();
				if(orderNo == null || "".equals(orderNo) || flag == false){// 没有编号或者流水重置
					sb.append(list.get(i).getCode());
				}else{// 有编号
					String nonew = orderNo.substring(sb.length(), (sb.length()+list.get(i).getRuleLength()));
					sb.append(String.format("%"+fillCharacter+length+"d", Integer.valueOf(nonew)+step));
				}
			}else if(list.get(i).getRuleCategory() == 3){// 时间
				 Date currentTime = new Date();
				 SimpleDateFormat formatter = new SimpleDateFormat(list.get(i).getCode());
				 String dateString = formatter.format(currentTime);
				 sb.append(dateString);
			}else{
				sb.append(list.get(i).getCode());
			}
			if(i < list.size()-1){
				sb.append(delimiter);
			}
		}
		return sb.toString();
	}

	@Override
	@Transactional
	public Integer insertRule(CoderulesPurposeEntity cpe) {
		Map<String, Object> usmap = new HashMap<String, Object>();
		usmap.put("purposeId", cpe.getPurposeId());
		usmap.put("facId", cpe.getFacId());
		Integer num = codeRulesMapper.findByPurposeId(usmap);
		if(num > 0){
			return -1;
		}
		codeRulesMapper.insertRule(cpe);
		List<CodeRulesEntity> ruleList = cpe.getRuleList();
		for(int i = 0;i<ruleList.size();i++){
			ruleList.get(i).setOrigin(cpe.getId());
			ruleList.get(i).setFacId(cpe.getFacId());;
			codeRulesMapper.insertDatels(ruleList.get(i));
		}
		return 1;
	}

	@Override
	@Transactional
	public Integer deleteRules(Map<String, Object> usmap) {
		codeRulesMapper.deleteDatels(usmap);
		
		return codeRulesMapper.deleteRules(usmap);
	}

	@Override
	public void rulesList(PageUtils<CoderulesPurposeEntity> pageinfo) {
		Long count = codeRulesMapper.findRulesCount(pageinfo);
		pageinfo.setTotal(count);
		if(count == 0){
			pageinfo.setData(new ArrayList<CoderulesPurposeEntity>());
		}else{
			pageinfo.setData(codeRulesMapper.rulesList(pageinfo));
		}
	}

	@Override
	public CoderulesPurposeEntity findDatels(Map<String, Object> usmap) {
		
		return codeRulesMapper.findRulesById(usmap);
	}

	@Override
	@Transactional
	public Integer updateCodeRules(CoderulesPurposeEntity cpe) {
		Map<String, Object> usmap = new HashMap<String, Object>();
		usmap.put("purposeId", cpe.getPurposeId());
		usmap.put("facId", cpe.getFacId());
		usmap.put("id", cpe.getId());
		Integer num = codeRulesMapper.findByPurposeId(usmap);
		if(num > 0){
			return -1;
		}
		
		usmap.put("ids", new Long[]{cpe.getId()});
		codeRulesMapper.deleteDatels(usmap);
		
		List<CodeRulesEntity> ruleList = cpe.getRuleList();
		for(int i = 0;i<ruleList.size();i++){
			ruleList.get(i).setOrigin(cpe.getId());
			ruleList.get(i).setFacId(cpe.getFacId());
			codeRulesMapper.insertDatels(ruleList.get(i));
		}
		
		return codeRulesMapper.updateCodeRules(cpe);
	}
}
